package com.huantai.common.util.http;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

/**
 * Http请求帮助类
 * 
 * @author Ma Chao
 * @version 2018年4月18日 上午11:29:13
 */
public class HttpUtil {
    /** 不允许使用对象调用静态方法 */
    private HttpUtil() {}

    /** 数据编码格式 */
    private static final String CHARSET = "utf-8";
    /***/
    private static final String HTTPS = "https://";
    /** Http调用成功的响应码 */
    private static final int SUCCESS_CODE = 200;

    /**
     * 使用POST方式请求接口
     * 
     * @param httpClient HttpClient
     * @param param 组织好的请求参数
     * @param url 接口的URL
     * @return HttpResponse 接口响应信息
     * @throws NoSuchAlgorithmException, KeyManagementException, IOException
     */
    public static HttpResponse post(HttpClient httpClient, List<NameValuePair> param,
                                    String url) throws KeyManagementException, NoSuchAlgorithmException, IOException {
        int statusCode = 0;
        String entityString = null;
        String message = null;

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(param, CHARSET));

        if (url.startsWith(HTTPS)) {
            httpClient.enableSSL();
        }
        org.apache.http.HttpResponse response = httpClient.getHttpClient().execute(httpPost);

        statusCode = response.getStatusLine().getStatusCode();
        if (SUCCESS_CODE == statusCode) {
            entityString = EntityUtils.toString(response.getEntity(), CHARSET);
        } else {
            message = response.getStatusLine().getReasonPhrase();
        }

        // 返回响应信息
        HttpResponse result = new HttpResponse();
        result.setEntityString(entityString);
        result.setMessage(message);
        result.setStatusCode(statusCode);
        return result;
    }

    /**
     * 
     * 自定义请求头信息后使用POST方式请求接口
     * 
     * @param httpClient HttpClient
     * @param httpPost 自定义Header的HttpPost
     * @param param 组织好的请求参数
     * @param url 接口的URL
     * @return HttpResponse 接口响应信息
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static HttpResponse post(HttpClient httpClient, HttpPost httpPost,
                                    List<NameValuePair> param, String url)
            throws KeyManagementException, NoSuchAlgorithmException, IOException {
        int statusCode = 0;
        String entityString = null;
        String message = null;

        httpPost.setEntity(new UrlEncodedFormEntity(param, CHARSET));

        if (url.startsWith(HTTPS)) {
            httpClient.enableSSL();
        }
        org.apache.http.HttpResponse response = httpClient.getHttpClient().execute(httpPost);

        statusCode = response.getStatusLine().getStatusCode();
        if (SUCCESS_CODE == statusCode) {
            entityString = EntityUtils.toString(response.getEntity(), CHARSET);
        } else {
            message = response.getStatusLine().getReasonPhrase();
        }

        // 返回响应信息
        HttpResponse result = new HttpResponse();
        result.setEntityString(entityString);
        result.setMessage(message);
        result.setStatusCode(statusCode);
        return result;
    }

    /**
     * 使用POST方式请求接口
     * 
     * @param httpClient HttpClient
     * @param jsonStr JSON字符串
     * @param url 接口的URL
     * @return HttpResponse 接口响应信息
     */
    public static HttpResponse postJson(HttpClient httpClient, String jsonStr,
                                        String url) throws KeyManagementException, NoSuchAlgorithmException, IOException {
        int statusCode = 0;
        String entityString = null;
        String message = null;

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(jsonStr, CHARSET));
        if (url.startsWith(HTTPS)) {
            httpClient.enableSSL();
        }
        org.apache.http.HttpResponse response = httpClient.getHttpClient().execute(httpPost);

        statusCode = response.getStatusLine().getStatusCode();
        if (SUCCESS_CODE == statusCode) {
            entityString = EntityUtils.toString(response.getEntity(), CHARSET);
        } else {
            message = response.getStatusLine().getReasonPhrase();
        }

        // 返回响应信息
        HttpResponse result = new HttpResponse();
        result.setEntityString(entityString);
        result.setMessage(message);
        result.setStatusCode(statusCode);
        return result;
    }

    /**
     * 使用GET方式请求接口
     * 
     * @param httpClient HttpClient
     * @param param 组织好的请求参数
     * @param url 接口的URL
     * @return HttpResponse 接口响应信息
     */
    public static HttpResponse get(HttpClient httpClient, List<NameValuePair> param,
                                   String url) throws KeyManagementException, NoSuchAlgorithmException, IOException {
        int statusCode = 0;
        String entityString = null;
        String message = null;

        if (null != param && !param.isEmpty()) {
            String requestParam = URLEncodedUtils.format(param, CHARSET);
            if (url.indexOf('?') == -1) {
                url += "?" + requestParam;
            } else {
                url += "&" + requestParam;
            }
        }

        HttpGet httpGet = new HttpGet(url);

        if (url.startsWith(HTTPS)) {
            httpClient.enableSSL();
        }
        org.apache.http.HttpResponse response = httpClient.getHttpClient().execute(httpGet);
        statusCode = response.getStatusLine().getStatusCode();
        if (SUCCESS_CODE == statusCode) {
            entityString = EntityUtils.toString(response.getEntity(), CHARSET);
        } else {
            message = response.getStatusLine().getReasonPhrase();
        }

        // 返回响应信息
        HttpResponse result = new HttpResponse();
        result.setEntityString(entityString);
        result.setMessage(message);
        result.setStatusCode(statusCode);
        return result;
    }
}
